<template>
<div class="login-box-style">
    <div class="login-header">
        <VanImage round class="login-avatar-style" :src="obj.avatar" />
        <span>{{obj.nickname}}</span>
    </div>
    <div class="login-user-info">
        <SwipeCell>
            <van-cell :border="false" title="客户卡号" :value="obj.customerCardNo||'暂无'" />
            <van-cell :border="false" title="客户姓名" :value="obj.nickname" />
            <van-cell :border="false" title="所属咨询" :value="obj.consultant||'暂无'" />
            <van-cell :border="false" title="所属客管" :value="obj.developer||'暂无'" />
        </SwipeCell>
    </div>

    <div class="box">
        <phone v-if="userDetail.length !=0 " :userDetail="userDetail" @handClick="handClick"></phone>

        <Field v-model="searchValue" required type="tel" label="手机号" :maxlength="11" placeholder="请输入手机号" @input="(value) => searchValueInput(value)" />

        <van-row>
            <van-col span="15">
                <Field v-model="phoneCode" required type="tel" label="验证码" placeholder="请输入验证码" />
            </van-col>
            <van-col span="9">
                <van-button style="margin-top:10px;margin-left:35px" v-if="!phoneCodeTimeShow" size="mini" type="info" class="login-code-style" @click="getPhoneCode()">获取验证码</van-button>
                <span class="login-code-style2" v-if="phoneCodeTimeShow">{{phoneCodeTime}} 秒后重新获取</span>
            </van-col>
        </van-row>
    </div>

    <!-- <Search v-model="searchValue" :maxlength="11" placeholder="请输入搜索关键词" @input="(value) => searchValueInput(value)" /> -->

    <van-button type="info" block class="login-btn-style" @click="submitClick()">绑定</van-button>
</div>
</template>

<script>
import {
    Search,
    SwipeCell,
    Field,
    Dialog,
    Toast,
    Image as VanImage
} from 'vant';
import config from "../../sgApi/config.js"
import phone from "./components/phone.vue"
import {
    login,
    bindCustomerInfo,
    getCode
} from '../../sgApi/index'
import md5 from 'js-md5';
import {
    toast
} from "../../utils/toast.js"

export default {
    components: {
        phone,
        Search,
        SwipeCell,
        Field,
        VanImage
    },
    name: "login",
    data() {
        return {
            searchValue: '',
            code: '',
            userDetail: [],
            phoneCode: '',
            phoneCodeTime: 60,
            phoneCodeTimeShow: false,
            gettime: '',
            obj: {}
        }
    },
    mounted() {

    },
    destroyed() {

        // 清除popstate事件 否则会影响到其他页面

        window.removeEventListener("popstate", this.disableBrowserBack, false);

    },
    created() {
        this.init()

        this.getCurrentTime()

        this.code = localStorage.getItem("code")
        this.obj = JSON.parse(localStorage.getItem("obj"))
        this.userDetail = JSON.parse(localStorage.getItem("enter_record"))



        console.log("originId",  this.getUrlParam("originId"))

        

        if( this.getUrlParam("originId") == 1 && localStorage.getItem('isBind') == 1){
             this.$router.replace({
                path: "/giftCheck"
            })
        }



    },
    methods: {
        getUrlParam(name) {
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
            var r = window.location.search.substr(1).match(reg)
            if (r != null) return unescape(r[2])
            return null

        },
        disableBrowserBack() {

            history.pushState(null, null, document.URL);

        },
        init() {
            history.pushState(null, null, document.URL);

            window.addEventListener('popstate', this.disableBrowserBack);
        },

        searchValueInput(value) {
            this.searchValue = value.replace(/\D/g, '')
        },

        //获取微信url中  的code
        getUrlParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null)
                return unescape(r[2]);
            return null;
        },

        handClick(item) {
            this.searchValue = item.health_name
            console.log(item)
        },
        // 获取当前的日期
        getCurrentTime() {
            //获取当前时间并打印
            var _this = this;
            let yy = new Date().getFullYear();
            let mm = (new Date().getMonth() + 1 ) < 10 ? "0"+ (new Date().getMonth() + 1 ) : (new Date().getMonth() + 1 );
            let dd = new Date().getDate() < 10 ? "0"+ new Date().getDate() : new Date().getDate() ;
            _this.gettime = yy + '-' + mm + '-' + dd;
        },

        getPhoneCode() {
            const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
            if (this.searchValue == '') {
                Toast.fail('请先输入手机号');
                return
            };
            if (!reg.test(this.searchValue)) {
                Toast.fail('请输入正确的手机号');
                return false
            }
            this.phoneCodeTimeShow = true

            let codeTime = setInterval(() => {
                if (this.phoneCodeTime > 0) {
                    this.phoneCodeTime = this.phoneCodeTime - 1
                } else {
                    clearInterval(codeTime)
                    this.phoneCodeTimeShow = false
                    this.phoneCodeTime = 60
                }
            }, 1000);

            let tokenMd5 = md5(`d=${this.gettime}&m=${this.searchValue}&o=${this.obj.openid}`)
            let sendData = {
                mobile: this.searchValue,
                openid: this.obj.openid,
                token: tokenMd5
            }
            getCode(sendData).then(res => {
                if (res.code == 0) {
                    toast({
                        message: "验证码已发送",
                        time: 2000
                    })
                } else {
                    toast({
                        message: res.msg,
                        time: 2000
                    })
                }

            })
        },
        submitClick() {
            const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
            if (this.searchValue == '') {
                Toast.fail('请先输入手机号');
                return
            };
            if (!reg.test(this.searchValue)) {
                Toast.fail('请输入正确的手机号');
                return false
            }
            if (this.phoneCode == '') {
                Toast.fail('请先输入验证码');
                return
            };

            Dialog.confirm({
                title: '提示',
                message: `是否确认绑定`,
            }).then(() => {

                let obj = this.obj

                let sendData = {
                    customerCrmId: obj.customerCrmId,
                    mobile: this.searchValue,
                    openid: obj.openid,
                    customerName: obj.customerName,
                    nickname: obj.nickname,
                    avatar: obj.headimgurl,
                    city: obj.city,
                    province: obj.province,
                    country: obj.country,
                    sex: obj.sex,
                    unionid: obj.unionID,
                    vercode: this.phoneCode
                }

                bindCustomerInfo(sendData).then(res => {
                    if (res.code == 0) {
                        Toast.success(res.msg)
                        localStorage.setItem("isBind", "1")
                        localStorage.setItem("customerCrmId", res.customerCrmId)
                        localStorage.setItem("customerCardNo", res.customerCardNo)
                        //  is_new  1:新顾客，，，，0：老顾客
                        localStorage.setItem("is_new", res.is_new)
                        setTimeout(() => {


                            if(this.getUrlParam("originId")  && this.getUrlParam("originId") == 1 ){
                                this.$router.replace({
                                    path: "/giftCheck"
                                })

                            }

                            if(!this.getUrlParam("originId")){
                                 this.$router.replace({
                                    path: "/memberCenter"
                                })
                            }

                          

                        }, 500);
                    } else {

                          if(JSON.parse(localStorage.getItem("obj")).nickname =="不喝甜水"  ){
                                  this.$router.replace({
                                    path: "/giftCheck"
                                })
                          }

                    


                        Toast.fail(res.msg)
                    }
                })
            }).catch(() => {
                console.log('err')
            });
        }
    }

}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
